package com.wangyadong.hobby.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * 线程通信用
 */
public class CountDownLatchesTest {
    private static final int nThreads = 3;
    private static final CountDownLatch latch = new CountDownLatch(nThreads);
    private static final CountDownLatch start = new CountDownLatch(1);


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
        Runnable runnable = () -> {
            try {
                System.out.println(" thread " + Thread.currentThread().getName() + " await count is" + latch.getCount());
                if (Thread.currentThread().getName().equals("pool-1-thread-3")) {
                    Thread.currentThread().interrupt();
                }
                start.await();
                Thread.sleep(1000);

                latch.countDown();
                System.out.println(" thread " + Thread.currentThread().getName() + " wake up" + latch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        IntStream.range(0, nThreads).forEach(t -> {
            executorService.execute(runnable);
        });
        Thread.sleep(500);
        start.countDown();
        System.out.println("  start.countDown();" + latch.getCount());
        latch.await();


        executorService.shutdownNow();

    }


}
